#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @File  : views.py
# @Author: Xuhao
# @Date  : 2017/12/4
# @Desc  : 


#

from flask import Flask, request, jsonify
from flask_restful import Api
from app.Modules.book_modules import NoverInfo
from app.Sql.sqlHelper import Sqlhelper
from app.common.Tool import Tool
from app.config import RULES
from app.spiders.HtmlPraser import Html_Parser

from app.resources.Book import BookDetail, BookList,BookSearching, BookTypeList, BookRecommend, BookSources,BookTuijian
from app.resources.FeedBack import FeedBackList, AddFeedBack
from app.resources.Vsersion import VersionInfo


app = Flask(__name__)
app.config["JSON_AS_ASCII"]=False
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"]=False
api = Api(app)

# 添加路由表

# 小说相关
api.add_resource(BookDetail, '/api/v2/BookDetail/')
api.add_resource(BookList, '/api/v2/booklist/')
api.add_resource(BookTypeList, '/api/v2/booktypelist/')
api.add_resource(BookRecommend, '/api/v2/bookRecommend')
api.add_resource(BookSources, '/api/v2/bookSource')
api.add_resource(BookSearching, '/api/v2/booksearching')
api.add_resource(BookTuijian, '/api/v2/booktuijian')

# 版本相关
api.add_resource(VersionInfo, '/api/v2/version')


# 意见反馈
api.add_resource(FeedBackList, '/api/v2/feedbacklist')
#api.add_resource(AddFeedBack, '/api/v2/feedback')


@app.route('/')
@app.route('/index')
def index():
    # POST:
    # request.form获得所有post参数放在一个类似dict类中,to_dict()是字典化
    # 单个参数可以通过request.form.to_dict().get("xxx","")获得
    # ----------------------------------------------------
    # GET:
    # request.args获得所有get参数放在一个类似dict类中,to_dict()是字典化
    # 单个参数可以通过request.args.to_dict().get('xxx',"")获得
    return 'Hello, world'

@app.errorhandler(404)
def not_found(error=None):
    message = {
            'status': 404,
            'message': 'Not Found: ' + request.url,
    }
    resp = jsonify(message)
    resp.status_code = 404

    return resp


@app.route('/api/fetchBookList', methods=['GET'])
def fetchBookList():
    '''
    获取小说列表
    :return: 
    '''
    if request.method == 'GET':
        jsondata = request.args.to_dict()
        categoryStr = jsondata['categoryStr']
        startID = jsondata['startID']
        count = jsondata['count']
        str = jsondata["encryption"]
        # if Tool.decodeStr(textStr=str) == False:
        #     return jsonify(
        #         {"result": {},
        #          "code": 201,
        #          "message": "权限验证失败"
        #          }
        #     )

        sql = Sqlhelper()
        data = sql.fetchBookList(categoryStr,startID=startID, count=count)
        if data != None:
            return jsonify({"result": {"bookList": data}, "code": 200, "message": "获取成功"})
        else:
            return jsonify({"result": {"data": {}}, "code": 201, "message": "获取失败"})



@app.route('/api/addfeedback', methods=['POST'])
def addfeedback():
    '''
    添加反馈
    :return:
    '''
    if request.method == 'POST':
        jsondata = request.form.to_dict()
        content = jsondata['content']
        title = jsondata['title']
        str = jsondata["encryption"]
        # if Tool.decodeStr(textStr=str) == False:
        #     return jsonify(
        #         {"result": {},
        #          "code": 201,
        #          "message": "权限验证失败"
        #          }
        #     )

        sql = Sqlhelper()

        ret = sql.addFeedBack(content, title)

        if ret == True:
            return jsonify(
                {"result": {},
                 "code": 200,
                 "message": "反馈成功"
                 }
            )
        else:
            return jsonify(
                {"result": {},
                 "code": 201,
                 "message": "反馈失败，请重试"
                 }
            )


@app.route('/api/fetchfeedback', methods=['GET'])
def fetchfeedback():
    '''
    获取反馈列表
    :return:
    '''
    if request.method == 'GET':
        jsondata = request.args.to_dict()

        str = jsondata["encryption"]
        # if Tool.decodeStr(textStr=str) == False:
        #     return jsonify(
        #         {"result": {},
        #          "code": 201,
        #          "message": "权限验证失败"
        #          }
        #     )

        sql = Sqlhelper()

        ret = sql.fetchFeedBack()

        if ret != None:
            return jsonify(
                {"result": {"feedback": ret},
                 "code": 200,
                 "message": "获取反馈列表成功"
                 }
            )
        else:
            return jsonify(
                {"result": {},
                 "code": 201,
                 "message": "获取反馈列表失败"
                 }
            )

@app.route('/api/findBook', methods=['GET'])
def findBook():
    '''
    收索小说
    :return:
    '''
    if request.method == 'GET':
        jsondata = request.args.to_dict()

        keyName = jsondata['bookName']
        str = jsondata["encryption"]
        # if Tool.decodeStr(textStr=str) == False:
        #     return jsonify(
        #         {"result": {},
        #          "code": 201,
        #          "message": "权限验证失败"
        #          }
        #     )

        sql = Sqlhelper()
        ret = sql.findBook(keyName=keyName)

        if ret != None:

            for dict in  ret:
                if dict["novelName"] == keyName:
                    sql = Sqlhelper()
                    sql.addHotsearchRank(keyName)
            return jsonify({"result": {"bookList": ret}, "code": 200, "message": "获取成功"})
        else:
            return jsonify(
                {"result": {},
                 "code": 201,
                 "message": "没有查询书籍"
                 }
            )


@app.route('/api/fetchhotSearch', methods=['GET'])
def fetchhotSearch():
    '''
    获取热门收索
    :return:
    '''
    if request.method == 'GET':
        jsondata = request.args.to_dict()

        count = jsondata["count"]
        str = jsondata["encryption"]
        # if Tool.decodeStr(textStr=str) == False:
        #     return jsonify(
        #         {"result": {},
        #          "code": 201,
        #          "message": "权限验证失败"
        #          }
        #     )


        sql = Sqlhelper()

        ret = sql.fetchHotSearchRankList(count=count)

        if ret != None:
            return jsonify({"result": {"ranklist": ret}, "code": 200, "message": "获取成功"})
        else:
            return jsonify(
                {"result": {},
                 "code": 201,
                 "message": "获取失败"
                 }
            )


@app.route('/api/versionControl', methods=['GET'])
def versionControl():
    '''
    版本控制
    :return:
    '''
    if request.method == 'GET':
        jsondata = request.args.to_dict()

        count = jsondata["version"]

        str = jsondata["encryption"]
        # if Tool.decodeStr(textStr=str) == False:
        #     return jsonify(
        #         {"result": {},
        #          "code": 201,
        #          "message": "权限验证失败"
        #          }
        #     )

        filtArray = ["(.?随.*|)(.?(梦|夢).*|)(.?小.*|)(.?(说|說)).+?(?=[\u4e00-\u9fa5]|”|“|\n|$|\r)",
                     "(//|\(|\（).*(ｗ|w|W|Ｗ|随梦小说网).+?(//|\)|\）|\n)"]
        dict = {"isalert": "0" ,
                "isforce": "0",
                "version": "2.0",
                "updataInfo": "修复BUG",
                "bannerCnt": "4",
                "isShowGoodReputation": "1",
                "filtration":filtArray,
                "appStoreURL":"itms-apps://itunes.apple.com/app/id1341590572"}

        return jsonify({"result": dict, "code": 200, "message": "获取成功"})




@app.route('/api/praserchapterlist', methods=['POST'])
def praserchapterlist():

    if request.method == 'POST':
        jsondata = request.form.to_dict()
        url = jsondata["url"]
        resonse = jsondata["resonse"]

        htmlParser = Html_Parser()

        if 'www.suimeng.la' in url:
            rules = RULES[1]
        else:
            rules = RULES[0]
        list = htmlParser.ChapterXpathPraser(url=url,response=resonse,rules=rules)


        return jsonify({"result": list, "code": 200, "message": "获取成功"})


@app.route('/api/bannerClick', methods=['POST'])
def bannerClick():

    if request.method == 'POST':
        jsondata = request.form.to_dict()
        UUID = jsondata["UUID"]
        date = jsondata["date"]

        sql = Sqlhelper()

        ret = sql.fetchUUID(UUID=UUID, date=date)

        if ret != None:
            sql1 = Sqlhelper()
            cnt = str(int(ret["cnt"]) + 1)
            sql1.updataUUID(UUID, date, cnt)

        else:
            sql2 = Sqlhelper()
            sql2.insertUUID(UUID, date, "1")
        return jsonify({"result": "", "code": 200, "message": "获取成功"})

if __name__ == '__main__':

    app.run(host='0.0.0.0', port=5001)


    #NoverInfo.fetchBookDetai()


    # htmlParser = Html_Parser()
    #
    # tmp =  htmlParser.ChapterXpathPraser(url="", response=text, rules=RULES[1])


    #http://www.biqukan.com/0_558/184926.html
    # url = "http://www.biqukan.com/0_558/184926.html"
    # r = requests.post(url)
    #
    #
    # tmp = re.compile(r'(.?<div id="content" class="showtxt">.+?(?=</div>))',re.S)
    #
    # tmp1 = re.findall(tmp, r.text)
    #
    # tmp2 = re.sub(r"&nbsp;", "", tmp1[0])
    #
    # tmp3 = re.sub(r"<br />", "\n  ", tmp2)
    #
    # tmp4 = re.sub(r'<div id="content" class="showtxt">', "", tmp3)
    #
    # print(tmp4)